require "rexml/document"

class JobsController < ApplicationController
  # GET /jobs
  # GET /jobs.json
  def index
    @jobs = Job.all

    respond_to do |format|
      format.html # index.html.erb
      format.json { render json: @jobs }
    end
  end

  # GET /jobs/1
  # GET /jobs/1.json
  def show
    @job = Job.find(params[:id])
    
    last_local_build_number = @job.builds.maximum('number')

    if last_local_build_number.nil?
      last_local_build_number = 0
    end

    response = RestClient.post "http://lfjenkins.swacorp.com/jenkins/job/#{@job.name}/api/xml", :tree => 'builds[number,result]'

    doc, remote_builds = REXML::Document.new(response), []
    doc.elements.each('freeStyleProject/build') do |b|
      
      build_number = b.get_elements('number')[0].get_text().value.to_i()
      build_result = b.get_elements('result')[0]
      
      unless build_result.nil? #check if a build is on going
        if build_number > last_local_build_number
          remote_builds << Build.new do |b|
            b.number = build_number
            b.result = build_result.get_text().value            
          end
        end
      end
    end
    
    unless remote_builds.empty?
      @job.builds << remote_builds
    end
    
    @builds = @job.builds.order('number desc').limit(20)
    
    remote_builds.each do |build|
      puts '*************************************************************************'
      puts 'New Build' + build.number.to_s()
      Thread.new do        
        tests_response = RestClient.post "http://lfjenkins.swacorp.com/jenkins/job/#{@job.name}/#{build.number}/testReport/api/xml", :tree => "suites[cases[className,status]]"        
               
        doc_build, test_results = REXML::Document.new(tests_response), []
        puts 'doc:'

        begin
        doc_build.elements.each('//suite/case') do |result|                    
          begin
            test_path = result.get_elements('className')[0].get_text().value            
          rescue => e
            puts 'test ERROR: 1 '+e.to_s()
            puts 'test ERROR: 2 '+result.to_s()            
          end
          
          begin
            test_status = result.get_elements('status')[0].get_text().value
          rescue => e
            puts 'test ERROR: 2.A '+e.to_s()
          end      
          
          test = Test.find_by_path test_path          
          if test.nil?
            test = Test.create(:path => test_path) #improve this transaction
          end
          puts 'new test: '+test.to_s()

          test_results << TestResult.new do |t|
            t.result = test_status
            t.test = test        
          end
        end
        rescue => e
          puts e
          puts "ERROR: 3"+e.to_s()
        end        
        #build.test_results << test_results
      end
      
    end
    
    respond_to do |format|
      format.html # show.html.erb
      format.json { render json: @job }
    end
  end

  # GET /jobs/new
  # GET /jobs/new.json
  def new
    @job = Job.new

    respond_to do |format|
      format.html # new.html.erb
      format.json { render json: @job }
    end
  end

  # GET /jobs/1/edit
  def edit
    @job = Job.find(params[:id])
  end

  # POST /jobs
  # POST /jobs.json
  def create
    @job = Job.new(params[:job])
    
    begin
      RestClient.get "http://lfjenkins.swacorp.com/jenkins/job/#{@job.name}/api/xml"
      respond_to do |format|
        if @job.save
          format.html { redirect_to @job, notice: 'Job was successfully created.' }
          format.json { render json: @job, status: :created, location: @job }
        else
          format.html { render action: "new" }
          format.json { render json: @job.errors, status: :unprocessable_entity }
        end
      end
    rescue RestClient::ResourceNotFound
      @job.errors[:name] = "The Job does not exist in Jenkins"
      respond_to do |format|
        format.html { render action: "new"}
        format.json { render json: @job.errors, status: :unprocessable_entity }
      end
    end
  end

  # PUT /jobs/1
  # PUT /jobs/1.json
  def update
    @job = Job.find(params[:id])

    respond_to do |format|
      if @job.update_attributes(params[:job])
        format.html { redirect_to @job, notice: 'Job was successfully updated.' }
        format.json { head :no_content }
      else
        format.html { render action: "edit" }
        format.json { render json: @job.errors, status: :unprocessable_entity }
      end
    end
  end

  # DELETE /jobs/1
  # DELETE /jobs/1.json
  def destroy
    @job = Job.find(params[:id])
    @job.destroy

    respond_to do |format|
      format.html { redirect_to jobs_url }
      format.json { head :no_content }
    end
  end
end
